package com.ssy.lingxi.member.merchant.api.handler.validator;


import com.ssy.lingxi.member.merchant.api.handler.annotation.DateTimeStringFormatAnnotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 时间日期格式字符串校验注解验证类
 * @author 万宁
 * @version 2.0.0
 * @date 2020-07-10
 */
public class DateTimeStringFormatValidator implements ConstraintValidator<DateTimeStringFormatAnnotation, String> {
    private String format = "yyyy-MM-dd HH:mm:ss";
    private boolean nullable = false;

    @Override
    public void initialize(DateTimeStringFormatAnnotation constraintAnnotation) {
        nullable = constraintAnnotation.nullable();
        format = constraintAnnotation.format();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || "".equals(value)) {
            return nullable;
        }

        try {
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern(format);
            LocalDateTime dt = LocalDateTime.parse(value, fmt);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
